<template>
  <div class="salaries">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="yyyy-MM"
            @change="handleSearch">
          </el-date-picker>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filters.department_id"
            placeholder="选择部门"
            clearable
            @change="handleSearch">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filters.status"
            placeholder="发放状态"
            clearable
            @change="handleSearch">
            <el-option label="未发放" value="未发放"></el-option>
            <el-option label="已发放" value="已发放"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="filters.employee_name"
            placeholder="搜索员工姓名"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button type="primary" @click="handleAdd">新增薪资记录</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 薪资列表 -->
    <el-table
      v-loading="loading"
      :data="salaries"
      border
      style="width: 100%">
      <el-table-column prop="employee_name" label="员工姓名" width="120"></el-table-column>
      <el-table-column prop="department_name" label="所属部门" width="120"></el-table-column>
      <el-table-column prop="year" label="年份" width="100"></el-table-column>
      <el-table-column prop="month" label="月份" width="100"></el-table-column>
      <el-table-column prop="base_salary" label="基本工资" width="120">
        <template slot-scope="scope">
          {{ scope.row.base_salary.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="bonus" label="奖金" width="120">
        <template slot-scope="scope">
          {{ scope.row.bonus.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="deductions" label="扣除" width="120">
        <template slot-scope="scope">
          {{ scope.row.deductions.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="total_salary" label="实发工资" width="120">
        <template slot-scope="scope">
          {{ scope.row.total_salary.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '已发放' ? 'success' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="payment_date" label="发放日期" width="120">
        <template slot-scope="scope">
          {{ scope.row.payment_date || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status === 'paid'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.per_page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 薪资表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm">
      <el-form
        ref="salaryForm"
        :model="salaryForm"
        :rules="rules"
        label-width="100px">
        <el-form-item label="员工" prop="employee_id">
          <el-select
            v-model="salaryForm.employee_id"
            filterable
            placeholder="选择员工">
            <el-option
              v-for="emp in employees"
              :key="emp.id"
              :label="emp.name"
              :value="emp.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年月" prop="year_month">
          <el-date-picker
            v-model="salaryForm.year_month"
            type="month"
            placeholder="选择月份"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="基本工资" prop="base_salary">
          <el-input-number
            v-model="salaryForm.base_salary"
            :min="0"
            :precision="2"
            :step="1000">
          </el-input-number>
        </el-form-item>
        <el-form-item label="奖金" prop="bonus">
          <el-input-number
            v-model="salaryForm.bonus"
            :min="0"
            :precision="2"
            :step="1000">
          </el-input-number>
        </el-form-item>
        <el-form-item label="扣除" prop="deductions">
          <el-input-number
            v-model="salaryForm.deductions"
            :min="0"
            :precision="2"
            :step="1000">
          </el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="salaryForm.status">
            <el-radio label="未发放">未发放</el-radio>
            <el-radio label="已发放">已发放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放日期" prop="payment_date" v-if="salaryForm.status === 'paid'">
          <el-date-picker
            v-model="salaryForm.payment_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Salaries',
  data() {
    return {
      // 表格数据
      salaries: [],
      loading: false,
      departments: [],
      employees: [],
      dateRange: [],
      filters: {
        department_id: '',
        status: '',
        employee_name: ''
      },
      pagination: {
        page: 1,
        per_page: 10,
        total: 0
      },

      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitting: false,
      salaryForm: {
        employee_id: '',
        year_month: '',
        base_salary: 0,
        bonus: 0,
        deductions: 0,
        status: '未发放',
        payment_date: ''
      },
      rules: {
        employee_id: [
          { required: true, message: '请选择员工', trigger: 'change' }
        ],
        year_month: [
          { required: true, message: '请选择年月', trigger: 'change' }
        ],
        base_salary: [
          { required: true, message: '请输入基本工资', trigger: 'blur' }
        ],
        bonus: [],
        deductions: [],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        payment_date: [
          { required: true, message: '请选择发放日期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchDepartments()
    this.fetchEmployees()
    this.fetchSalaries()
  },
  methods: {
    // 获取部门列表
    async fetchDepartments() {
      try {
        const response = await axios.get('/api/departments/')
        this.departments = response.data
      } catch (error) {
        this.$message.error('获取部门列表失败')
      }
    },

    // 获取员工列表
    async fetchEmployees() {
      try {
        const response = await axios.get('/api/employees/')
        this.employees = response.data.items
      } catch (error) {
        this.$message.error('获取员工列表失败')
      }
    },

    // 获取薪资列表
    async fetchSalaries() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          per_page: this.pagination.per_page,
          ...this.filters
        }
        if (this.dateRange && this.dateRange.length === 2) {
          const [startYear, startMonth] = this.dateRange[0].split('-')
          params.year = parseInt(startYear)
          params.month = parseInt(startMonth)
        }
        const response = await axios.get('/api/salaries/', { params })
        this.salaries = response.data.items
        this.pagination.total = response.data.total
      } catch (error) {
        this.$message.error('获取薪资列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.fetchSalaries()
    },

    // 分页
    handleSizeChange(val) {
      this.pagination.per_page = val
      this.fetchSalaries()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchSalaries()
    },

    // 新增薪资记录
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增薪资记录'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑薪资记录
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑薪资记录'
      this.salaryForm = {
        ...row,
        deductions: row.deductions,
        year_month: `${row.year}-${String(row.month).padStart(2, '0')}`
      }
      // Ensure status is correctly mapped for editing
      if (this.salaryForm.status === 'pending' || this.salaryForm.status === '未发放') {
          this.salaryForm.status = '未发放';
      } else if (this.salaryForm.status === 'paid' || this.salaryForm.status === '已发放') {
          this.salaryForm.status = '已发放';
      }
      this.dialogVisible = true
    },

    // 删除薪资记录
    handleDelete(row) {
      this.$confirm('确认删除该薪资记录吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`/api/salaries/${row.id}/`)
          this.$message.success('删除成功')
          this.fetchSalaries()
        } catch (error) {
          this.$message.error(error.response?.data?.error || '删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.salaryForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            const [year, month] = this.salaryForm.year_month.split('-')
            const data = {
              ...this.salaryForm,
              year: parseInt(year),
              month: parseInt(month)
            }
            delete data.year_month

            // Always ensure the status sent to backend is '未发放' or '已发放'
            let finalStatus = '';
            if (data.status === '未发放') {
                finalStatus = '未发放';
            } else if (data.status === '已发放') {
                finalStatus = '已发放';
            } else if (data.status === 'pending') { // Handle legacy/unexpected 'pending'
                finalStatus = '未发放';
            } else if (data.status === 'paid') { // Handle legacy/unexpected 'paid'
                finalStatus = '已发放';
            } else {
                // Fallback for any other unexpected values, default to '未发放'
                finalStatus = '未发放';
            }
            data.status = finalStatus;

            if (this.isEdit) {
              await axios.put(`/api/salaries/${this.salaryForm.id}/`, data)
              this.$message.success('更新成功')
            } else {
              await axios.post('/api/salaries/', data)
              this.$message.success('创建成功')
            }
            this.dialogVisible = false
            this.fetchSalaries()
          } catch (error) {
            this.$message.error(error.response?.data?.error || '操作失败')
          } finally {
            this.submitting = false
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.salaryForm?.resetFields()
      this.salaryForm = {
        employee_id: '',
        year_month: '',
        base_salary: 0,
        bonus: 0,
        deductions: 0,
        status: '未发放',
        payment_date: ''
      }
    }
  }
}
</script>

<style scoped>
.salaries {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 